# 自动处理环境问题
try:
    import textual
except:
    import subprocess 
    result = subprocess.run(['pip', 'install', '-r', 'requirements.txt'], capture_output=True, text=True)  
    if result.returncode == 0:  
        print(result.stdout)  
    else:   
        print(result.stderr)
        import os,signal                            
        pid = os.getpid()                           #获取自身pid
        os.kill(pid,signal.SIGTERM)                 #关闭自身进程

from textual.app import*
from textual.widgets import*
from textual.containers import*
from textual.reactive import reactive
from textual.widgets import Welcome
from tools import *          # 这是自己的库

class Page1_GIFTool(Static):
    '''Oled图片转换工具
    功能1:将GIF提取为单张图片
    功能2:将图片转换为xbm
    功能3:将xbm内数组合并为.h文件'''
    def __init__(self):
        super().__init__(id="page1")
    def compose(self) -> ComposeResult:  
        """Compose the label and a switch."""  
        yield Button("提取GIF->PNG",id="btu_gif_rgb",tooltip="彩色图片",classes="button_style")
        yield Button("提取GIF->BMP",id="btu_gif_bw", tooltip="黑白图片",classes="button_style")  
        yield Button("转换GIF文件夹XBM格式",id="btu_folderxbm",tooltip="",classes="button_style")  
        yield Button("生成GIF文件夹数组",id="btu_floderarray",tooltip="单击此按钮生成.h数组",classes="button_style")    
        yield Button("退出程序",id="btu_quit", tooltip="单击此按钮退出",classes="button_style")

class Page2_IMGTool(Static):
    '''单独图片准换工具'''
    def __init__(self,):
        super().__init__(id="page2")
    def compose(self) -> ComposeResult:  
        """Compose the label and a switch."""  
        yield Button("转换单个文件XBM格式",id="btu_filexbm",tooltip="",classes="button_style")
        yield Button("生成文件数组",id="btu_filearray",tooltip="单击此按钮生成.h数组",classes="button_style")
        yield Button("退出程序",id="btu_quit", tooltip="单击此按钮退出",classes="button_style")

class Page3_Setting(Static):
    '''程序设置'''
    def compose(self) -> ComposeResult:
        """Compose the label and a switch."""
        yield Label("版本信息 Version 0.1")
        # yield Button("设置生成图像分辨率",id="btu_set_res")
        yield Button("跳转至开源链接",id="btu_jump_url",classes="button_style")

class OledTabsApp(App):
    '''显示主界面与逻辑绑定'''
    CSS_PATH = "OledToolUi.tcss"
    TITLE = "Oled图片转换工具"
    BINDINGS = [("d", "toggle_dark", "切换显示模式")]
    def __init__(self):
        super().__init__()                    # 初始化基类
        self.path_select = SelectPath()       # 实例化类
        self.tools = tool_img()               # 实例化类
    def compose(self) -> ComposeResult:
        yield Header()                  #显示标题
        yield Footer()                  #显示底部工具栏
        with TabbedContent():
            with TabPane("GIF工具", id="page1"):
                yield ScrollableContainer(Page1_GIFTool())
            with TabPane("IMG工具", id="page2"):
                yield ScrollableContainer(Page2_IMGTool())
            with TabPane("设置", id="page3"):
                yield ScrollableContainer(Page3_Setting())
    def action_toggle_dark(self) -> None:
        '''切换显示模式'''
        self.dark = not self.dark
    def on_button_pressed(self,event:Button.Pressed):
        '''button事件'''
        button_id = event.button.id
        if button_id == "btu_set_res":
            self.tools = tool_img((50,50))
        elif button_id == "btu_jump_url":
            url_jump()
        elif button_id == "btu_gif_rgb":
            path_gif = self.path_select.select_file(".gif")
            extract_frames(path_gif,"png")

        elif button_id == "btu_gif_bw":
            path_gif = self.path_select.select_file(".gif")
            extract_frames(path_gif,"bmp")

        elif button_id == "btu_filexbm":
            img_path = self.path_select.select_file(".png .jpg .jpeg .bmp")
            save_xbm = self.path_select.select_save_file(img_path)
            self.tools.img_xbm(img_path,save_xbm)
            
        elif button_id == "btu_folderxbm":
            img_floder = self.path_select.select_folder()
            asyncio.create_task(self.tools.floder_xbm(img_floder))

        elif button_id == "btu_filearray":
            xbm_file = self.path_select.select_file(".xbm")
            self.tools.merge_file(xbm_file)

        elif button_id == "btu_floderarray":
            xbm_floder = self.path_select.select_folder()
            open_folder_path = self.tools.merge_folder(xbm_floder)
            if open_folder_path != '':
                open_folder(open_folder_path)

        elif button_id == "btu_quit":
            sys.exit()

if __name__ == "__main__":

    OledTabsApp().run()